﻿Imports ZedGraph

Public Class Form2


    Dim p1 As Decimal = 21.011
    Dim p2 As Decimal = 21.011
    Dim p3 As Decimal = 0

    Public k1 As Decimal = 42.41
    Public k2 As Decimal = 777.5
    Public k3 As Decimal = 292.24
    Public k4 As Decimal = 0.92
    Public k5 As Decimal = -0.02

    Public valor1 As Decimal = 21.011
    Public valor2 As Decimal = 0.545
    Public valor3 As Decimal = 21.011
    Public valor4 As Decimal = 0.545
    Public valor5 As Decimal = 0.545
    Public valor6 As Decimal = 0.545



    '=(K1*B^K4-(K2*VALO1+K3)*(1-EXP(-K5*VALOR2/(VALOR3+VALOR4))))*(VALOR1/VALOR5)^VALOR6


    Dim myPane As GraphPane

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        ReDim variables(4)
        ReDim rango(4, 1)

        TP1.Text = k1
        TP2.Text = k2
        TP3.Text = k3
        TP4.Text = k4
        TP5.Text = k5


        TK1.Text = k1
        TK2.Text = k2
        TK3.Text = k3
        TK4.Text = k4
        TK5.Text = k5



    End Sub

    Sub Calcular()

        variables(0) = TP1.Text
        variables(1) = TP2.Text
        variables(2) = TP3.Text
        variables(3) = TP4.Text
        variables(4) = TP5.Text

        rango(0, 0) = 0.001 ' 4,6
        rango(0, 1) = 5 'maximo

        rango(1, 0) = 0.001 ' 5,6
        rango(1, 1) = 5 'maximo

        rango(2, 0) = 0.001 ' 6,6
        rango(2, 1) = 5 'maximo

        rango(3, 0) = 0.001 ' 6,6
        rango(3, 1) = 5 'maximo

        rango(4, 0) = 0.001 ' 6,6
        rango(4, 1) = 5 'maximo

 
        Minimize = True
        Constrain = True

 
        Minimize = True
        Constrain = True
        Minimization1(Me)  'Nelder-Mead
        'obj_Excel.Run("Hoja94.Minimization1")

        ' Obj_Libro.Save()
        'obj_Excel.Visible = True



    End Sub
    Sub Minimization1(ByRef Frm As Form2)
        'Call Nelder-Mead algorithm
        Dim x
        Dim xsol As Object, ysol As Double, tol As Double, n As Integer
        Dim i As Integer, j As Integer, itmax As Long, its As Long
        Dim tmp
        tol = 0.00001 'tolerancia de la minimizacion puede ser cambiada
        n = UBound(variables)
        itmax = 3200    'Nº maximo de iteraciones se pueden modificar
        ReDim x(n)
        For i = 0 To n
            x(i) = variables(i)
        Next i

        'If rango <> "" Then
        'input box constrain
        'If Range(RangeBox).Cells.Count <> 2 * n Then
        ' MsgBox "invalid number of constrains", vbCritical
        'Exit Sub
        'End If

        getConstrainBox(Box)
        XScaling(Box)
        'rescaling variables
        If Constrain = True Then
            For i = 0 To n
                x(i) = x(i) / Xscale(i)
            Next i
            Constrain = True
        Else
            'rescaling variables
            XScaling(x)
            Constrain = False
        End If

        'ReDim s(n + 1, n)  'simplex
        Dim s(n + 1, n) As Double

        If Constrain = False Then
            'choose a starting point with no constrain
            For i = 0 To n
                For j = 0 To n
                    s(i, j) = x(j)
                    If i = j Then
                        s(i, j) = s(i, j) + 0.1
                    End If
            Next j, i
        Else
            'choose a starting point with constrains
            Constrain_Point(x)
            For i = 0 To n
                For j = 0 To n
                    s(i, j) = (x(j) + Box(j, 0) + Box(j, 1)) / 3
                    If i = j Then
                        s(i, j) = s(i, j) + 0.1 * (Rnd() - 0.5)
                    End If

            Next j, i
        End If

        '    On Error Resume Next

        Call NMSimplex(Me, s, xsol, ysol, tol, itmax, its, Constrain)

    End Sub
    Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit



        p1 = TP1.Text.Replace(".", ",")
        p2 = TP2.Text.Replace(".", ",")
        p3 = TP3.Text.Replace(".", ",")

        Dim A As Decimal = (DataGridView1(0, e.RowIndex).Value)
        Dim B As Decimal = (DataGridView1(1, e.RowIndex).Value)
        Dim C As Decimal = (valor1 * (1 - Math.Exp(-p2 * A ^ p3)) * valor2)
        Dim D As Decimal = 0
        Try
            D = (B - C) ^ 2
        Catch ex As Exception

        End Try


        DataGridView1(2, e.RowIndex).Value = FormatNumber(C, 2)
        DataGridView1(3, e.RowIndex).Value = FormatNumber(D, 2)


    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Button1.Enabled = False

        Calcular()
        GeneraGrafico()

        Button1.Enabled = True

    End Sub
    Sub GeneraGrafico()

        Dim X1(DataGridView1.Rows.Count) As Double
        Dim Y1(DataGridView1.Rows.Count) As Double

        Dim X2(DataGridView1.Rows.Count) As Double
        Dim Y2(DataGridView1.Rows.Count) As Double

        Dim i As Integer

        'Set up some data
        Dim points As New PointPairList()
        Dim regressionLine__1 As New PointPairList()

        For i = 0 To DataGridView1.Rows.Count - 2
            points.Add(DataGridView1(0, i).Value, DataGridView1(2, i).Value)
            regressionLine__1.Add(DataGridView1(0, i).Value, DataGridView1(1, i).Value)
        Next

        If ZedGraphControl1.GraphPane.CurveList.Count > 0 Then
            ZedGraphControl1.GraphPane.CurveList.RemoveAt(1)
            ZedGraphControl1.GraphPane.CurveList.RemoveAt(0)
        End If

        myPane = ZedGraphControl1.GraphPane



        'Get a new LineItem and set it up
        Dim myCurve As LineItem
        myCurve = New LineItem("", points, Color.DarkBlue, SymbolType.None)
        myCurve.Symbol.Size = 5
        myCurve.Symbol.Fill.Color = Color.DarkBlue
        myCurve.Symbol.Fill.IsVisible = True
        myCurve.Line.IsVisible = True
        myCurve.Line.StepType = StepType.NonStep

        myPane.Title.Text = "ISOTERMA HEAP"
        myPane.Title.FontSpec.Size = 14
        myPane.XAxis.Title.Text = "Cu Acuoso, g/L"
        myPane.YAxis.Title.Text = "Cu Orgánico, g/L"
        'Add the new lineItem to the graph pane
        myPane.CurveList.Add(myCurve)
        'Get the axis to auto update
        myPane.AxisChange()


        Dim RegressionLine__2 As New LineItem("Fitted Line", regressionLine__1, Color.Red, SymbolType.Circle)
        'RegressionLine__2.Line.StepType = StepType.NonStep
        RegressionLine__2.Symbol.Size = 5
        RegressionLine__2.Symbol.Fill.Color = Color.Red
        RegressionLine__2.Symbol.Fill.IsVisible = True
        RegressionLine__2.Line.Color = Color.Red
        RegressionLine__2.Line.Width = 3
        RegressionLine__2.Line.IsVisible = False
        myPane.CurveList.Add(RegressionLine__2)
        myPane.Legend.IsVisible = False


        Using g As Graphics = Me.CreateGraphics()
            ZedGraphControl1.MasterPane.ReSize(g, ZedGraphControl1.MasterPane.Rect)
        End Using



        ZedGraphControl1.AxisChange()
        ZedGraphControl1.Refresh()
    End Sub


    Public Shared Function Variance(ByVal Data As Double()) As Double
        Dim sum As Double = 0
        Dim average As Double = Data.Average()
        For Each value As Double In Data
            sum += Math.Pow((value - average), 2)
        Next
        Dim result As Double = sum / (Data.GetLength(0))
        Return result
    End Function

    Public Shared Function CoVariance(ByVal data1 As Double(), ByVal data2 As Double()) As Double
        Dim result As Double = 0
        Dim avgX As Double = data1.Average()
        Dim avgY As Double = data2.Average()
        For i As Integer = 0 To data1.GetLength(0) - 1
            result = result + ((data1(i) - avgX) * (data2(i) - avgY))
        Next
        Return result / data1.GetLength(0)
    End Function
    Private Sub PlotRegressionLine(ByVal slope As Double, ByVal offset As Double, ByVal min As Double, ByVal max As Double)

        Dim regressionLine__1 As New PointPairList()
        regressionLine__1.Add(min, (min * slope) + offset)
        regressionLine__1.Add(max, (max * slope) + offset)
        Dim RegressionLine__2 As New LineItem("Fitted Line", regressionLine__1, Color.Black, SymbolType.None)
        RegressionLine__2.Line.StepType = StepType.NonStep
        RegressionLine__2.Line.Color = Color.Red
        RegressionLine__2.Line.Width = 3
        myPane.CurveList.Add(RegressionLine__2)
        myPane.Legend.IsVisible = False
    End Sub

    Private Sub AddNumbers(ByVal rSquared As Double, ByVal slope As Double, ByVal ofset As Double)
        Dim text As New TextObj("R-Squared: " & Math.Round(rSquared, 2) & vbLf & "Slope: " & Math.Round(slope, 2) & vbLf & "Offset: " & Math.Round(ofset, 2), 0.2, 0.2, CoordType.ChartFraction)
        myPane.GraphObjList.Add(text)
    End Sub

    Private Sub CreateGraph(ByVal zgc As ZedGraphControl)
        ' get a reference to the GraphPane

        Dim myPane As GraphPane = zgc.GraphPane

        ' Set the Titles

        myPane.Title.Text = "My Test Graph" & vbLf & "(For CodeProject Sample)"
        myPane.XAxis.Title.Text = "My X Axis"
        myPane.YAxis.Title.Text = "My Y Axis"

        ' Make up some data arrays based on the Sine function

        Dim x As Double, y1 As Double, y2 As Double
        Dim list1 As New PointPairList()
        Dim list2 As New PointPairList()
        For i As Integer = 0 To 35
            x = CDbl(i) + 5
            y1 = 1.5 + Math.Sin(CDbl(i) * 0.2)
            y2 = 3.0 * (1.5 + Math.Sin(CDbl(i) * 0.2))
            list1.Add(x, y1)
            list2.Add(x, y2)
        Next

        ' Generate a red curve with diamond

        ' symbols, and "Porsche" in the legend

        Dim myCurve As LineItem = myPane.AddCurve("Porsche", list1, Color.Red, SymbolType.Diamond)

        ' Generate a blue curve with circle

        ' symbols, and "Piper" in the legend

        Dim myCurve2 As LineItem = myPane.AddCurve("Piper", list2, Color.Blue, SymbolType.Circle)

        ' Tell ZedGraph to refigure the

        ' axes since the data have changed

        zgc.AxisChange()
    End Sub

    Private Sub TK1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TK1.TextChanged
        TP1.Text = TK1.Text
    End Sub

    Private Sub TK2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TK2.TextChanged
        TP2.Text = TK2.Text
    End Sub

    Private Sub TK3_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TK3.TextChanged
        TP3.Text = TK3.Text
    End Sub
End Class
